# coding=utf-8
__author__ = 'Anderson Farias'
import re
import datetime
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _

PHONE_REGEX = r'\(\d{2}\) \d{4}-\d{4}'
CPF_REGEX = r'\d{3}.\d{3}.\d{3}-\d{2}'
CNPJ_REGEX = r'\d{2}.\d{3}.\d{3}/\d{4}-\d{2}'
POSTAL_CODE_REGEX = r'\d{5}-\d{3}'

CPF_MESSAGE = _("The CPF should be in the format 000.000.000-00.One 0(zero) represents one digit.")
PHONE_MESSAGE = _("The phone should be in the format (00) 0000-0000.")
CNPJ_MESSAGE = _("The CNPJ should be in the format 00.000.000/0000-00.One 0(zero) represents one digit.")
POSTAL_CODE_MESSAGE = _("The postal code should be in the format 00000-000. One 0(zero) represents one digit.")


def validate_only_white_spaces(value):
    if value and not value.strip():
        raise ValidationError(_("Must have at least one character"))


def validate_past_date(value):
    if value >= datetime.date.today():
        raise ValidationError(_("Must be a past date"))


def validate_future_date(value):
    if value <= datetime.date.today():
        raise ValidationError(_("Must be a future date"))


def validate_cpf(value):
    weights = [10, 9, 8, 7, 6, 5, 4, 3, 2]
    if value and re.compile(CPF_REGEX).match(value):
        sum = 0
        value = value.replace('.', '').replace('-', '')

        for i, c in enumerate(value):
            if i == 9:
                break
            sum += int(c) * weights[i]

        mod = sum % 11
        first_digit = 0 if mod < 2 else 11 - mod

        weights = [11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
        sum = 0
        for i, c in enumerate(value):
            if i == 10:
                break
            if i == 9:
                sum += first_digit * weights[i]
            else:
                sum += int(c) * weights[i]

        mod = sum % 11

        second_digit = 0 if mod < 2 else 11 - mod

        if (int(value[9]) != first_digit) or (int(value[10]) != second_digit):
            raise ValidationError(_('Invalid CPF'))


def validate_cnpj(value):
    weights = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
    if value and re.compile(CNPJ_REGEX).match(value):
        sum = 0
        value = value.replace('.', '').replace('-', '').replace('/', '')

        for i, c in enumerate(value):
            if i == 12:
                break
            sum += int(c) * weights[i]

        mod = sum % 11
        first_digit = 0 if mod < 2 else 11 - mod

        weights = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
        sum = 0
        for i, c in enumerate(value):
            if i == 13:
                break
            if i == 12:
                sum += first_digit * weights[i]
            else:
                sum += int(c) * weights[i]

        mod = sum % 11

        second_digit = 0 if mod < 2 else 11 - mod

        if (int(value[12]) != first_digit) or (int(value[13]) != second_digit):
            raise ValidationError(_('Invalid CNPJ'))